package com.tledu.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClient4 {
    public static void main(String[] args) throws IOException {
        // json提交的方式
        // get 、 post 、 put 、delete 、  options
        // 接口文档
        //      接口地址，请求方式，请求的参数，请求体的类型
        String url = "http://1.117.81.216/test/post-json";
        // 1. 创建HttpCLient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 构建请求
        HttpPost httpPost = new HttpPost(url);

        // 构建json字符串
        //  {"name":"cyrus","age":18,"hobby":"玩桌游"}
        String jsonStr = "{\"name\":\"cyrus\",\"age\":18,\"hobby\":\"玩桌游\"}";
        StringEntity stringEntity = new StringEntity(jsonStr, "utf8");
        httpPost.setEntity(stringEntity);
        // 指定一下请求头
        httpPost.addHeader("Content-Type","application/json");

        // 3. 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 4. 拿到结果
        int code = response.getStatusLine().getStatusCode();
        if (code != 200) {
            httpPost.abort();
            System.out.println("出错了");
        }else {
            // 获取请求体
            HttpEntity entity1 = response.getEntity();
            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
            response.close();
        }
    }
}
